const bcrypt = require('bcrypt');
const logger = require('../config/logger');

async function createUser(request, reply) {
  const { 
    name, 
    email, 
    password, 
    avatar, 
    phone, 
    facebookId, 
    role 
  } = request.body;

  try {
    // 检查邮箱是否已存在
    const existingUser = await this.prisma.user.findUnique({
      where: { email }
    });

    if (existingUser) {
      logger.warn('创建用户失败：邮箱已被注册', { email });
      return reply.code(400).send({ error: '该邮箱已被注册' });
    }

    // 对密码进行加密
    const hashedPassword = await bcrypt.hash(password, 10);

    // 创建新用户
    const user = await this.prisma.user.create({
      data: {
        name,
        email,
        passwordHash: hashedPassword,
        avatar,
        phone,
        facebookId,
        role: role || 'user', // 默认角色为普通用户
        balance: 0, // 初始余额为0
        totalStudyTime: 0, // 初始学习时间为0
        totalReservations: 0 // 初始预约次数为0
      },
      select: {
        id: true,
        name: true,
        avatar: true,
        email: true,
        phone: true,
        facebookId: true,
        role: true,
        balance: true,
        totalStudyTime: true,
        totalReservations: true,
        createdAt: true,
        updatedAt: true
      }
    });
    
    logger.info('新用户创建成功', { userId: user.id, email: user.email });
    return reply.code(201).send(user);
  } catch (error) {
    logger.error('创建用户失败', {
      error: error.message,
      stack: error.stack,
      request: request.body
    });
    return reply.code(500).send({ error: '创建用户失败' });
  }
}

async function getUsers(request, reply) {
  try {
    const users = await this.prisma.user.findMany({
      select: {
        id: true,
        name: true,
        avatar: true,
        email: true,
        phone: true,
        facebookId: true,
        role: true,
        balance: true,
        totalStudyTime: true,
        totalReservations: true,
        createdAt: true,
        updatedAt: true
      }
    });
    return reply.send(users);
  } catch (error) {
    logger.error(error);
    return reply.code(500).send({ error: '获取用户列表失败' });
  }
}

async function getUser(request, reply) {
  const { id } = request.params;
  try {
    const user = await this.prisma.user.findUnique({
      where: { id: parseInt(id) },
      select: {
        id: true,
        name: true,
        avatar: true,
        email: true,
        phone: true,
        facebookId: true,
        role: true,
        balance: true,
        totalStudyTime: true,
        totalReservations: true,
        createdAt: true,
        updatedAt: true,
        memberships: {
          select: {
            id: true,
            membershipType: true,
            balance: true,
            expiresAt: true
          }
        },
        orders: {
          select: {
            id: true,
            status: true,
            orderStartTime: true,
            orderEndTime: true
          }
        }
      }
    });
    
    if (!user) {
      return reply.code(404).send({ error: '用户不存在' });
    }
    return reply.send(user);
  } catch (error) {
    logger.error(error);
    return reply.code(500).send({ error: '获取用户信息失败' });
  }
}

async function updateUser(request, reply) {
  const { id } = request.params;
  const updateData = request.body;
  
  try {
    if (updateData.password) {
      updateData.passwordHash = await bcrypt.hash(updateData.password, 10);
      delete updateData.password;
    }
    
    const user = await this.prisma.user.update({
      where: { id: parseInt(id) },
      data: updateData,
      select: {
        id: true,
        name: true,
        avatar: true,
        email: true,
        phone: true,
        facebookId: true,
        role: true,
        balance: true,
        totalStudyTime: true,
        totalReservations: true,
        createdAt: true,
        updatedAt: true
      }
    });
    
    return reply.send(user);
  } catch (error) {
    if (error.code === 'P2025') {
      return reply.code(404).send({ error: '用户不存在' });
    }
    logger.error(error);
    return reply.code(500).send({ error: '更新用户信息失败' });
  }
}

async function deleteUser(request, reply) {
  const { id } = request.params;
  try {
    await this.prisma.user.delete({
      where: { id: parseInt(id) }
    });
    return reply.code(204).send();
  } catch (error) {
    if (error.code === 'P2025') {
      return reply.code(404).send({ error: '用户不存在' });
    }
    logger.error(error);
    return reply.code(500).send({ error: '删除用户失败' });
  }
}

async function getStudyRanking(request, reply) {
  try {
    const users = await this.prisma.user.findMany({
      select: {
        id: true,
        name: true,
        avatar: true,
        totalStudyTime: true,
        totalReservations: true
      },
      orderBy: {
        totalStudyTime: 'desc'
      },
      take: 50 // 限制返回前50名
    });

    return reply.send(users);
  } catch (error) {
    logger.error(error);
    return reply.code(500).send({ error: '获取学习排行榜失败' });
  }
}

module.exports = {
  createUser,
  getUsers,
  getUser,
  updateUser,
  deleteUser,
  getStudyRanking
};